package com.lepu.app.fun.bbs.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;

import com.lepu.app.fun.bbs.adapter.AdapterBbs;
import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.main.bean.BeanFocus;
import com.lepu.app.widget.FocusOneView;
import com.lepu.app.widget.FocusView;
import com.lepu.pasm.R;

public class FragmentBbs extends BaseFragment implements AsyncRequest,
		OnRefreshListener, OnLoadListener, Observer {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";
	private static final String REQUEST_DATA_FOCUS = "request_data_focus";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;
	
	private static final int MSG_DATA_FOCUS_SUCCESS = 30;

	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterBbs mDataAdapter = null;
	private ArrayList<BeanBbs> mDataArrayList = null;
	
	private int mCurrentPage = 1;
	private boolean mInitDataSuccess = false;

	private View mMainView = null;

	private String mCurrentDate = "";

	public boolean mNeedRefresh = false;

	public int mTopicType = 1;
	
	private FocusView mFocusViewArticle = null;
	private FocusOneView mFocusOneViewArticle = null;

	private boolean mIsRefreshData = true;
	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(R.layout.bbs_fragment, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@SuppressLint("DefaultLocale")
	@Override
	public void onDestroy() {
		
		String key = String.format("%s_%d", ObserverConst.NOTIFY_MOTHER_POST_CHANGE,mTopicType);
        ObserverManager.getInstance().removeObserver(key);
        
        super.onDestroy();
		mInitDataSuccess = false;
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mFocusViewArticle != null) {
			mFocusViewArticle.onResumeViewPager();
		}

        if(mTopicType == 1){ //精选
        	UmengHelper.OnPageStart(UmengEvent.page_luntan_retie);
        }else if(mTopicType == 2){//康复专区
        	UmengHelper.OnPageStart(UmengEvent.page_luntan_kangfuzhuanqu);
        }else if(mTopicType == 3){//养生天地
        	UmengHelper.OnPageStart(UmengEvent.page_luntan_yangshengtiandi);
        }
		
	}

	@Override
	public void onPause() {
		super.onPause();

		if (mFocusViewArticle != null) {
			mFocusViewArticle.onPauseViewPager();
		}
		
        if(mTopicType == 1){ //精选
        	UmengHelper.OnPageEnd(UmengEvent.page_luntan_retie);
        }else if(mTopicType == 2){//康复专区
        	UmengHelper.OnPageEnd(UmengEvent.page_luntan_kangfuzhuanqu);
        }else if(mTopicType == 3){//养生天地
        	UmengHelper.OnPageEnd(UmengEvent.page_luntan_yangshengtiandi);
        }
	}
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {

				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
					}
				}, 100);
				//一个activity加入多个fragment，有些手机不能自动加载更多，需要调一下这个方法，就可以了！！！
				if(mTopicType == 1){  //热帖添加轮播图
					requestFocus(true);
				}else{
					request(false);
				}
			}
		}
	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
				noDataLayout.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						request(false);
					}
				});
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	@SuppressWarnings("unused")
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView.findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint({ "ResourceAsColor", "DefaultLocale" })
	private void init() {
		mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
											R.color.color_listview_refresh_2,
											R.color.color_listview_refresh_3,
											R.color.color_listview_refresh_4);
		mDataArrayList = new ArrayList<BeanBbs>();
		
		Bundle data = getArguments();
		
		mTopicType = data.getInt("Type");
		
		String key = String.format("%s_%d", ObserverConst.NOTIFY_MOTHER_POST_CHANGE,mTopicType);
        ObserverManager.getInstance().addObserver(key, this);
	}

	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = "";

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (LoginUtil.checkIsLogin()) {
				params.put("UserID", LoginUtil.getUserId());
			} else {
				params.put("UserID", -1);
			}
			
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			if(mTopicType == 1){ //热帖
				url = Setting.getBbsHotListUrl();
			}else if(mTopicType == 2){//支架人生
				url = Setting.getBbsListUrl();
				params.put("ForumID", 1);
				params.put("ThreadClassID", 0);
			}else if(mTopicType == 3){//支架术后
				url = Setting.getBbsListUrl();
				params.put("ForumID", 2);
				params.put("ThreadClassID", 0);
			}
			

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}
	
	//请求轮播图
	public void requestFocus(boolean isRefreshData) {
		mIsRefreshData = isRefreshData;
		String url = Setting.getArticleListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("ACIDList", "27");
			params.put("RefreshTime", "");
			params.put("SortDirection", "DESC");
			
			int version = AppManager.getVersionCode(getActivity(), getActivity().getPackageName());
			params.put("ClientVersion", String.valueOf(version));
			
			params.put("PageIndex", 1);
			params.put("PageSize", 100);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, REQUEST_DATA_FOCUS, true,false,true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				
				ArrayList<BeanBbs> dataList = (ArrayList<BeanBbs>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList.clear();
					mDataArrayList.addAll(dataList);
					
					ImageView tempImageView = new ImageView(getActivity());
					mDataListView.addHeaderView(tempImageView);
					mDataAdapter = new AdapterBbs(getActivity(),mDataArrayList,mTopicType,false);
					mDataListView.setAdapter(mDataAdapter);
					
					mDataListView.removeHeaderView(tempImageView);
					
					mInitDataSuccess = true;
				} else {
					//UIHelper.showToast(getActivity(), R.string.no_data);
                    showHideNoDataLayout(true);
					
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}

				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);
				
				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
					}
				}, 100);

				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanBbs> dataMoreList = (ArrayList<BeanBbs>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
				    mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					//UIHelper.showToast(getActivity(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_FOCUS_SUCCESS:
				if(mTopicType == 1){   //只有热帖添加轮播图
					ArrayList<BeanFocus> articleList = (ArrayList<BeanFocus>) msg.obj;
					if (articleList != null && articleList.size() > 0) {

						if (mFocusViewArticle != null) {
							mDataListView.removeHeaderView(mFocusViewArticle);
						}
						
						if(mFocusOneViewArticle != null){
							mDataListView.removeHeaderView(mFocusOneViewArticle);
						}

						ArrayList<BeanFocus> articleListFocus=new ArrayList<BeanFocus>();
						if(articleList.size() > 1){
							if(articleList.size() > 10){
								for(int i=0; i<10; i++){
									articleListFocus.add(articleList.get(i));
								}
								
								articleList.clear();
								articleList.addAll(articleListFocus);
							}
							
							mFocusViewArticle = new FocusView(getActivity(),articleList,FocusView.TYPE_DEFAULT,mGoogleRefreshLayout);
								
							mDataListView.addHeaderView(mFocusViewArticle);
						}else{
							if(articleList.size() == 1){
								mFocusOneViewArticle = new FocusOneView(getActivity(), articleList);
								mDataListView.addHeaderView(mFocusOneViewArticle);
							}
						}
						
					}
				}
				
				if(mIsRefreshData){
					// 请求列表数据
					request(false);
				}else{
					if(mDataAdapter != null){
						mDataAdapter.notifyDataSetChanged();
					}
				}
				
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		requestFocus(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			mCurrentDate = BeanBbs.parseJsonDate((String) data);
			ArrayList<BeanBbs> dataArraylist = BeanBbs.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mCurrentDate = BeanBbs.parseJsonDate((String) data);
			ArrayList<BeanBbs> dataMoreArraylist = BeanBbs.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mDataArrayList.addAll(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_FOCUS)) {
			// 解析json data
			ArrayList<BeanFocus> dataArraylist = BeanFocus.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_FOCUS_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} else if (object.equals(REQUEST_DATA_FOCUS)) {
			// 解析json data
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_FOCUS_SUCCESS;
			mHandler.sendMessage(msg);
		}
	}

	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		request(false);
	}

}
